package edu.unh.sustain;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class ShowPlanActivity extends Activity
{
	String baseURL = "http://www.google.com/maps?ie=UTF8&f=d&dirflg=r&hl=en";
	String pointA, pointB;
	String leave, leaveDate, leaveTime;
	WebView mWebView;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.showplan);
	    
	    Bundle extras = getIntent().getExtras();
    	
    	if( extras != null )
    	{
    		try
    		{
    			pointA = extras.getString("pointa");
    			pointB = extras.getString("pointb");
    			leaveDate = extras.getString("leaveDate");
    			leave = extras.getString("leave");
    			leaveTime = extras.getString("leaveTime");
    			
    			pointA = URLEncoder.encode(pointA, "UTF-8");
    			pointB = URLEncoder.encode(pointB, "UTF-8");
    			leaveDate = URLEncoder.encode(leaveDate, "UTF-8");
    			leaveTime = URLEncoder.encode(leaveTime, "UTF-8");

	    		if(leave.equals("Leave"))
	    			leave = "dep";
	    		else
	    			leave = "arr";
    		}
    		catch(UnsupportedEncodingException e)
    		{
    			System.err.println("something is wrong");
    			System.exit(1);
    		}
    	}
    	
	    StringBuilder url = new StringBuilder( baseURL );
	    url.append("&saddr=").append(pointA).append("&daddr=").append(pointB).append("&ttype=").append(leave).append("&date=").append(leaveDate).append("&time=").append(leaveTime);
	    mWebView = (WebView) findViewById(R.id.gtransit);
	    mWebView.getSettings().setJavaScriptEnabled(true);
	    mWebView.loadUrl(url.toString());
	    mWebView.setWebViewClient(new WebViewClient()
	    {
	    	/**
	    	 * loads URLs within the app, instead of the native browser
	    	 */
			public boolean shouldOverrideUrlLoading(WebView view, String url)
			{
				view.loadUrl(url);
				return false;
			}
	    });
	}
	
	/**
	 * Handles the back button in the webview.  If it can go back to a previous
	 * page, it does. If not, it will return to the Transportation menu.
	 */
	@Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
	{
        if(event.getAction() == KeyEvent.ACTION_DOWN)
        {
            switch(keyCode)
            {
	            case KeyEvent.KEYCODE_BACK:
	                if(mWebView.canGoBack() == true)
	                {
	                    mWebView.goBack();
	                }
	                else
	                {
                		finish();
	                }
	                return true;
            }
        }
        
        return super.onKeyDown(keyCode, event);
    }
}
